package com.nineclock.system.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.system.dto.SysRegisterDTO;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.mapper.SysUserMapper;
import com.nineclock.system.pojo.SysUser;
import com.nineclock.system.service.SysSmsService;
import com.nineclock.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Map;

@Service
@Transactional
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysSmsService sysSmsService;
    @Override
    public SysUserDTO queryUser(String username) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername , username)
                .or()
                .eq(SysUser::getMobile , username);
        wrapper.eq(SysUser::getStatus,1);

        SysUser sysUser = sysUserMapper.selectOne(wrapper);
        if (sysUser!=null){
            return BeanHelper.copyProperties(sysUser,SysUserDTO.class);
        }
        return null;
    }

    @Override
    public void register(SysRegisterDTO registerDTO) {
        // 参数校验
        if(registerDTO == null || StringUtils.isEmpty(registerDTO.getMobile())
                || StringUtils.isEmpty(registerDTO.getPassword())
                || StringUtils.isEmpty(registerDTO.getCheckcode())){

            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        Boolean result = sysSmsService.checkMessage(registerDTO.getCheckcode(), registerDTO.getMobile(), SMSConstant.SMS_TYPE_REGISTER);
        if (!result){
            throw new NcException(ResponseEnum.INVALID_VERIFY_CODE);
        }
        SysUser sysUser = new SysUser();
        sysUser.setPassword(new BCryptPasswordEncoder().encode(registerDTO.getPassword()));
        sysUser.setMobile(registerDTO.getMobile());
        sysUser.setCreateTime(new Date());
        sysUser.setUpdateTime(new Date());
        sysUser.setStatus((short)1);
        //sysUser.setLastLoginCompanyId(0L);
        sysUserMapper.insert(sysUser);
    }
}